package top.wilsonlv.jaguar.cloud.auth.oauth2;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;
import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * @author lvws
 * @since 2022/5/13
 */
@Component
@RequiredArgsConstructor
public class RedisAuthorizationCodeServices extends RandomValueAuthorizationCodeServices {

    private static final String AUTHORIZATION_CODE_KEY_PRE = "AuthorizationCode:";

    private final RedisTemplate<String, Serializable> redisTemplate;

    @Override
    protected void store(String code, OAuth2Authentication authentication) {
        redisTemplate.boundValueOps(AUTHORIZATION_CODE_KEY_PRE + code).set(authentication);
    }

    @Override
    protected OAuth2Authentication remove(String code) {
        String key = AUTHORIZATION_CODE_KEY_PRE + code;
        Serializable oauth2Authentication = redisTemplate.boundValueOps(key).get();
        if (oauth2Authentication != null) {
            redisTemplate.delete(key);
        }
        return (OAuth2Authentication) oauth2Authentication;
    }
}